package com.aaa.controller;

import com.aaa.entity.Info;
import com.aaa.entity.MyReturn;
import com.aaa.service.InfoService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * (Info)表控制层
 *
 * @author
 * @since 2022-05-27 10:05:51
 */
@RestController
@RequestMapping("infoService")
public class InfoController {
    /**
     * 服务对象
     */
    @Resource
    private InfoService infoService;
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 根据ip地址查询最后十条监控信息
     * @create time: 2022/6/17 9:58
     * @param info
     * @return MyReturn
     */
    @RequestMapping("queryInfoLast")
    public MyReturn queryInfoLast(Info info ){
        List<Info> infoList = infoService.queryInfoLast(info);
        MyReturn myReturn = new MyReturn();
        myReturn.setCode(0);
        //按照id进行排序
        List<Info> infos = infoList.stream().sorted(Comparator.comparing(Info::getId)).collect(Collectors.toList());
        myReturn.setData(infos);
        return myReturn;
    }
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 查询所有的info
     * @create time: 2022/5/27 10:50
     * @return
     */
    @RequestMapping("findAllInfo")
    @ResponseBody
    public Object findAllInfo(){
        List<Info> infoList = infoService.findAllInfo();
        return infoList;
    }

    /**
     * 分页查询
     *
     * @param info 筛选条件
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Info>> queryByPage(Info info, Integer page ,Integer limit) {
        PageRequest pageRequest=  PageRequest.of(page-1,limit);
        return ResponseEntity.ok(this.infoService.queryByPage(info, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Info> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.infoService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param info 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Info> add(Info info) {
        return ResponseEntity.ok(this.infoService.insert(info));
    }

    /**
     * 编辑数据
     *
     * @param info 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Info> edit(Info info) {
        return ResponseEntity.ok(this.infoService.update(info));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.infoService.deleteById(id));
    }

}

